import 'dart:math' as math;
import 'package:flutter/material.dart';

class MyFlipWiget extends StatefulWidget {
  MyFlipWiget({Key key, this.from, this.to}) : super(key: key);
  final Widget from;
  final Widget to;
  @override
  MyFlipWigetState createState() => MyFlipWigetState(from, to);
}

class MyFlipWigetState extends State<MyFlipWiget>
    with SingleTickerProviderStateMixin {
  AnimationController controller;
  Animation<double> animation;
  MyFlipWigetState(this.from, this.to);
  Widget from;
  Widget to;
  bool ishow = false;

  @override
  void initState() {
    
    controller = AnimationController(
      duration: Duration(milliseconds: 1000),
      vsync: this,
    )..addListener(() => {}); // 监听动画变更，更新页面

    // 定义动画更新区间的值
    animation = Tween<double>(begin: 0, end: 360.0).animate(controller);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: animateBuild(),
      ),
    );
  }

  // 动画小部件
  Widget animateBuild() {
    return AnimatedBuilder(
      animation: animation, // 动画效果
      child: this.to,
      builder: (BuildContext context, Widget child) {
        print(math.pi * animation.value / 360);
        return Transform(
          transform: Matrix4.identity()..setEntry(3, 2, 0.002) // 第三参数定义视图距离，值越小物体就离你越远，看着就有立体感
            // 旋转Y轴角度，pi为圆半径，animation.value为动态获取的动画值
            ..rotateY(math.pi * animation.value / 360),
          alignment: FractionalOffset.center, // 以轴中心开始动画
          child: animation.value < 180 ? this.from : child,
        );
      },
    );
  }

  void onClickEleBox() {
    if (animation.value < 360) {
      controller.forward();
      return;
    }
    controller.reverse(from: 360);
  }
}


// 封装的文本组件Widget
class TextWidget extends StatefulWidget {
  final Key key;

  // 接收一个Key
  TextWidget(this.key);

  @override
  State<StatefulWidget> createState() => TextWidgetState();
}

class TextWidgetState extends State<TextWidget> with SingleTickerProviderStateMixin{
  String _text = "11";

  @override
  Widget build(BuildContext context) {
    return new Text(_text);
  }

  void onPressed(int count) {
    setState(() => _text = count.toString());
  }
}